//
//  WSJSportBeginViewController.m
//  RunningMan
//
//  Created by dllo on 16/5/21.
//  Copyright © 2016年 WSJ. All rights reserved.
//

#import "WSJSportBeginViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "WSJSportDataView.h"

#import "WSJSliderView.h"

#import "RMDataModel.h"
#import "RMDataModelTool.h"
#import <AVFoundation/AVSpeechSynthesis.h>


@interface WSJSportBeginViewController ()
<
MKMapViewDelegate,
CLLocationManagerDelegate
>
// 倒计时
@property(nonatomic, retain) UILabel *timeCountDownLabel;
@property(nonatomic, retain) NSTimer *downTimer;
@property(nonatomic, assign) NSInteger timeCount;
//-----
@property(nonatomic, retain) MKMapView *mapView; // 地图
@property(nonatomic, retain) CLLocationManager *locationManager;
@property(nonatomic, retain) NSTimer *mapTimer; // 跑步定时器
@property(nonatomic, assign) BOOL isHidden; //
@property(nonatomic, retain)UIButton *upDownButton;

@property(nonatomic, retain) WSJSportDataView *sportDataView;


@property (nonatomic, retain) CLLocation *prevLocation;
@property (nonatomic, assign) CGFloat sumDistance;
@property(nonatomic, assign) NSInteger mapTimeLength;

@property(nonatomic, retain)WSJSliderView *sliderView;

//-----------------------------------------
@property(nonatomic, retain)RMCoreData *coreDataManager;
@property(nonatomic, retain)NSString *timestamp;
@property(nonatomic, retain)NSString *longitude;
@property(nonatomic, retain)NSString *latitude;
@property(nonatomic, retain)NSString  *altitude;
@property(nonatomic, retain)NSMutableArray *locationArr;
@property(nonatomic, retain)NSMutableArray *speedArr;

@end

@implementation WSJSportBeginViewController

- (NSMutableArray *)locationArr
{
    if (!_locationArr) {
        _locationArr = [NSMutableArray array];
    }
    return _locationArr;
}

- (NSMutableArray *)speedArr
{
    if (!_speedArr) {
        _speedArr = [NSMutableArray array];
    }
    return _speedArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.sumDistance = 0;
    self.mapTimeLength = 0;

    
    [self addCLLocationManager];
    [self addWSJSportDataView];
    
    self.coreDataManager = [RMCoreData defaultCoreDataManager];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self addTimeCountDownView];
}

#pragma  倒计时效果
-(void)addTimeCountDownView{

    self.timeCount = 3;
    self.timeCountDownLabel = [[UILabel alloc] initWithFrame:self.view.bounds];
    self.timeCountDownLabel.backgroundColor = [UIColor blackColor];
    self.timeCountDownLabel.textAlignment = 1;
    self.timeCountDownLabel.textColor = [UIColor whiteColor];
    self.timeCountDownLabel.text = [NSString stringWithFormat:@"%ld", self.timeCount];
    self.timeCountDownLabel.font = [UIFont systemFontOfSize:150];
    [self.view addSubview:self.timeCountDownLabel];
    self.downTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeChange) userInfo: nil repeats:YES];
//        AVSpeechSynthesizer *av = [[AVSpeechSynthesizer alloc]init];
//        AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc]initWithString:@"three,two,one,ready go"];
//        AVSpeechSynthesisVoice *vocie = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CHN"];
//        utterance.voice = vocie;
//        utterance.volume = 1.0;
//        utterance.pitchMultiplier = 1.1;
//        utterance.rate = AVSpeechUtteranceMinimumSpeechRate;
//        [av speakUtterance:utterance];
    
}


#pragma 倒计时 的定时器方法
-(void)timeChange{
    self.timeCount--;
    self.timeCountDownLabel.text = [NSString stringWithFormat:@"%ld", self.timeCount];
    if (self.timeCount < 0) {
        [self.downTimer invalidate];
        [self.timeCountDownLabel removeFromSuperview];
        [self addMapView];
    }
}


#pragma  添加CLLocationManager
-(void)addCLLocationManager{
    if ([[UIDevice currentDevice].systemVersion doubleValue] > 8.0) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    //------------
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    // [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager startUpdatingLocation];
    [self.locationManager startUpdatingHeading];
    [self.locationManager location];
    
    MKCoordinateSpan theSpan;
    theSpan.latitudeDelta = 0.05;
    theSpan.longitudeDelta = 0.05;
    MKCoordinateRegion theRegion;
    theRegion.center = [[_locationManager location] coordinate];
    theRegion.span = theSpan;
    [_mapView setRegion:theRegion];
    
    if (![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse) {
        
        [self.locationManager requestWhenInUseAuthorization];
    }
}
#pragma 添加地图
-(void)addMapView{
  
    self.mapView = [[MKMapView alloc ] init];
    self.mapView.frame = CGRectMake(0, 0, WIDTH , (HEIGHT) / 4);
    self.mapView.delegate = self;
    self.mapView.zoomEnabled = YES;
    self.mapView.scrollEnabled = YES;
    [self.view addSubview:self.mapView];
    // self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    self.mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
    self.mapView.mapType = MKMapTypeStandard ;
    self.mapView.showsUserLocation = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionMap)];
    [self.mapView addGestureRecognizer:tap];
    //------------
    [self addMapTimer];
    
    
    self.upDownButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.upDownButton.frame = CGRectMake(WIDTH - 60 , HEIGHT / 4 - 60, 40, 40);
    [self.upDownButton setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [self.upDownButton addTarget:self action:@selector(tapActionMap) forControlEvents:UIControlEventTouchUpInside];
    [self.mapView addSubview:self.upDownButton];
}

#pragma 点加 WSJSportDataView 视图
-(void)addWSJSportDataView{
    self.sportDataView = [[WSJSportDataView alloc] init];
    self.sportDataView.frame = CGRectMake(0, HEIGHT / 4, WIDTH, HEIGHT / 4 * 3);
    [self.view addSubview:self.sportDataView];
    
    [self.sportDataView.stopButton addTarget:self action:@selector(stopButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.sportDataView.startButton addTarget:self action:@selector(startButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.sportDataView.endButton addTarget:self action:@selector(endButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.sportDataView.lockButton addTarget:self action:@selector(lockButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.sliderView = [[WSJSliderView alloc] initWithFrame:CGRectMake(WIDTH / 2 - 120, self.sportDataView.frame.size.height - 150, 240, 40)];
    self.sliderView.hidden = YES;
    [self.sportDataView addSubview:_sliderView];
    
    // ----注册通知-----
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeSlider) name:@"123" object:nil];

}


#pragma 地图 的定时器
-(void)addMapTimer{
    
    self.mapTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(mapTimerAction) userInfo:nil repeats:YES];
}

#pragma 地图 的定时器方法
-(void)mapTimerAction{
    
    self.mapTimeLength++;
    NSInteger hour = self.mapTimeLength / 3600;
    NSInteger min = self.mapTimeLength % 3600 / 60;
    NSInteger sec = self.mapTimeLength % 60;
    self.sportDataView.timeLabel.text =  [NSString stringWithFormat:@"%02ld:%02ld:%02ld",hour, min,sec];

    [self.speedArr addObject:self.sportDataView.speedLabel.text];
}

#pragma  定位失败时激发的方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"定位失败: %@",error);
}




#pragma MKMapView 的协议方法  --- 更新用户位置，只要用户改变则调用此方法（包括第一次定位到用户位置）
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    
    //NSLog(@"您的当前位置:经度：%f,纬度：%f",userLocation.location.coordinate.longitude,userLocation.location.coordinate.latitude);
    //设置地图显示范围(如果不进行区域设置会自动显示区域范围并指定当前用户位置为地图中心点)
    [self.mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    MKCoordinateSpan span = MKCoordinateSpanMake(0.01, 0.01);//缩放比例(0.01--0.05)
    MKCoordinateRegion region = MKCoordinateRegionMake(userLocation.location.coordinate, span);
    [_mapView setRegion:region animated:true];
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    // course：该属性表示当前设备前进的方向。该值为0°表示向北，90°表示向东，180°表示向南，270°表示向西。
    
     NSLog(@"您的当前位置:经度：%f,纬度：%f,海拔：%f,航向：%f,速度：%f, 时间 : %@, 方向：%f,",newLocation.coordinate.longitude,newLocation.coordinate.latitude,newLocation.altitude,newLocation.course,newLocation.speed, newLocation.timestamp, newLocation.course);
   
    
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

    CLLocation* newLocation = [locations lastObject];
    [self.locationArr addObject:newLocation];

    if(newLocation.horizontalAccuracy < kCLLocationAccuracyHundredMeters)
    {
        if(self.prevLocation)
        {
            // 计算本次定位数据与上次定位数据之间的时间差
           // NSTimeInterval dTime = [newLocation.timestamp
           //                         timeIntervalSinceDate:self.prevLocation.timestamp];
            // 累计行车时间
            //  self.sumTime += dTime;
            // 计算本次定位数据与上次定位数据之间的距离
            CGFloat distance = [newLocation
                                distanceFromLocation:self.prevLocation];
            // 如果距离小于1米，则忽略本次数据，直接返回该方法
            if(distance < 1.0f)
            {
                return;
            }
            // 累加移动距离
            self.sumDistance += distance / 1000;
            // 计算移动速度，将米/秒换算成千米/小时，需要乘以3.6
            //CGFloat speed = distance / dTime * 3.6;
            // 计算平均速度
            //  CGFloat avgSpeed = self.sumDistance / self.sumTime * 3.6;
            //  NSString * speedFeedback = [NSString stringWithFormat:
            // @"当前速度为：%g千米/小时，平均速度为:%g千米/小时。合计移动:%g千米",
            // speed , avgSpeed , self.sumDistance / 1000];
  
        }
        self.prevLocation = newLocation;
    }
    
       self.sportDataView.distanceLabel.text  = [NSString stringWithFormat:@"%0.2f", self.sumDistance];
       self.sportDataView.speedLabel.text = [NSString stringWithFormat:@"%0.2f", newLocation.speed];
    
      self.longitude = [NSString stringWithFormat:@"%f", newLocation.coordinate.longitude];
      self.latitude = [NSString stringWithFormat:@"%f", newLocation.coordinate.latitude];
      self.altitude = [NSString stringWithFormat:@"%f", newLocation.altitude];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm:ss"];
   self.timestamp = [formatter stringFromDate:newLocation.timestamp];
 

}
//-----------------


#pragma 地图下拉方法
-(void)tapActionMap{
    if (self.isHidden == NO) {
        self.mapView.frame = CGRectMake(0, 0, WIDTH, HEIGHT / 6 * 5);
        self.sportDataView.frame = CGRectMake(0, HEIGHT / 6 * 5 , WIDTH, HEIGHT / 4 * 3);
        self.upDownButton.frame = CGRectMake(WIDTH - 60 , HEIGHT / 6 * 5 - 60, 40, 40);
        
    } else{
        self.mapView.frame = CGRectMake(0, 0, WIDTH , (HEIGHT) / 4);
        self.sportDataView.frame = CGRectMake(0, HEIGHT / 4 , WIDTH, HEIGHT / 4 * 3);
        self.upDownButton.frame = CGRectMake(WIDTH - 60 , HEIGHT / 4 - 60, 40, 40);
    }
    self.isHidden = ! self.isHidden;
}



#pragma WSJSportDataView 中按钮的点击方法

-(void)stopButtonAction{
    
    self.sportDataView.startButton.hidden = NO;
    self.sportDataView.endButton.hidden = NO;
    self.sportDataView.stopButton.hidden = YES;
    self.sportDataView.lockButton.hidden = YES;
    [self.mapTimer invalidate];
    [self.locationManager stopUpdatingLocation];
    
}
-(void)startButtonAction{
    
    self.sportDataView.endButton.hidden = YES;
    self.sportDataView.startButton.hidden = YES;
    self.sportDataView.stopButton.hidden = NO;
     self.sportDataView.lockButton.hidden = NO;
    [self addMapTimer];
    [self.locationManager startUpdatingLocation];
    
}
-(void)endButtonAction{
    
  
    
    RunData *runData = [NSEntityDescription insertNewObjectForEntityForName:@"RunData" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    runData.distance = self.sportDataView.distanceLabel.text;
    runData.runtime = [NSString stringWithFormat:@"%ld", self.mapTimeLength];
    runData.timestamp  = self.timestamp;
    runData.speed = self.sportDataView.speedLabel.text;
    runData.longitude = self.longitude;
    runData.latitude = self.latitude;
    runData.altitude = self.altitude;
    
    RMDataModel *model = [[RMDataModel alloc] init];
    model.locationArr = self.locationArr;
    model.speedArr = self.speedArr;
    [RMDataModelTool archiveRMDataModelInPlist:model];
    
    NSLog(@"===%@", self.speedArr);

    
    [self.coreDataManager saveContext];
    
    [self.mapTimer invalidate];
    [self.locationManager stopUpdatingLocation];
  
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}

-(void)lockButtonAction{
    self.sliderView.hidden = NO;
    self.sportDataView.lockButton.hidden = YES;
    self.sportDataView.stopButton.hidden = YES;
}

-(void)removeSlider{
    
    self.sliderView.hidden = YES;
    self.sportDataView.stopButton.hidden = NO;
    self.sportDataView.lockButton.hidden = NO;
}

-(void)dealloc{
    // ----移除通知----
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"123" object:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
